<?php

if (!defined('TOBBIVM'))
	header('location:/template/notrepassing.php');
/**
 * This file is part of TobbiVMShop.
 *
 * TobbiVMShop is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TobbiVMShop is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TobbiVMShop.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * payment: Paypal
 *
 * @version    $Id$
 * @package    TobbiVM-Shop
 * @copyright  Copyright (C) 2012
 * @author     Norbert Gebert
 * @license    GPL3
 */

/**
 * Returns price if availiable 
 */
function paypal($refCart)
{
	language::setTextDomain('paypal.payment');
	
	// Set ordernumber
	db::getInstance()->where('config_key', 'ordernumber');
	$row = db::getInstance()->getOne('config');
	$_SESSION['ordernumberx'] = $row['config_value'];

	$data = Array('config_value' => $_SESSION['ordernumberx'] + 1);
	db::getInstance()->where('config_key', 'ordernumber');
	db::getInstance()->update('config', $data);

	// Get customer-data
	db::getInstance()->where('orderer_id', $_SESSION['ordererIdx']);
	$customer = db::getInstance()->getOne('orderer');
	
	db::getInstance()->where('payment_name', $_SESSION['paymentx']);
	$row = db::getInstance()->getOne('payment');
	$config = $row['payment_config'];
	
	$_SESSION['trackingnumberx'] = $_SESSION['ordernumberx'] . '-' . time();

	// Set all parameter for paypal
	if (!empty($config))
	{
		$variablen = array('sandbox', 'domain', 'developer_account_email',
		 'api_username', 'api_password', 'api_signature');
		$configRows = array();
		$value = array();
		$configRows = explode('|', $config);
		$rowx = array();
		$a = 0;
		foreach ($configRows as $row)
		{
			$value = explode(':', $row);
			if ($a === 1)
			{
				$$variablen[$a] = 'http://' . $value[1];
			}
			else
			{
				$$variablen[$a] = $value[1];
			}
			$a++;
		}
	}

	// Enable error reporting if running in sandbox mode.
	if ($sandbox)
	{
		error_reporting(E_ALL | E_STRICT);
		ini_set('display_errors', '1');
	}
	// Setting PayPal API Version
	$api_version = '109.0';
	/*
	 * Setting PayPal Application ID
	 */
	$application_id = $sandbox ? 'APP-80W284485P519543T' : '';

	/*
	 * Payflow Gateway API Credentials
	 */
	$payflow_username = $sandbox ? 'SANDBOX_PAYFLOW_USERNAME' : 'LIVE_PAYFLOW_USERNAME';
	$payflow_password = $sandbox ? 'SANDBOX_PAYFLOW_PASSWORD' : 'LIVE_PAYFLOW_PASSWORD';
	$payflow_vendor = $sandbox ? 'SANDBOX_PAYFLOW_VENDOR' : 'LIVE_PAYFLOW_VENDOR';
	$payflow_partner = $sandbox ? 'SANDBOX_PAYFLOW_PARTNER' : 'LIVE_PAYFLOW_PARTNER';

	/*
	 * PayPal REST API Credentials
	 */
	$rest_client_id = $sandbox ? 'SANDBOX_CLIENT_ID' : 'LIVE_CLIENT_ID';
	$rest_client_secret = $sandbox ? 'SANDBOX_CLIENT_ID' : 'LIVE_SECRET_ID';

	/*
	 * PayPal Finance Portal API
	 * These are credentials used for obtaining a PublisherID used in 
	 * Bill Me Later Banner code. As of now, these are specialized API's and 
	 * you must obtain credentials directly from a PayPal rep.
	 */
	$finance_access_key = $sandbox ? 'SANDBOX_ACCESS_KEY' : 'LIVE_ACCESS_KEY';
	$finance_client_secret = $sandbox ? 'SANDBOX_CLIENT_SECRET' : 'LIVE_CLIENT_SECRET';
	/**
	 * Third Party User Values
	 * These can be setup here or within each caller directly 
	 * when setting up the PayPal object.
	 */
	// If making calls on behalf a third party, 
	// their PayPal email address or account ID goes here.
	$api_subject = '';
	$device_id = '';
	$device_ip_address = $_SERVER['REMOTE_ADDR'];

	// Call paypal
	// Include required library files.
	require_once('plugins/payment/paypal/paypal.class.php');
	require_once('plugins/payment/paypal/paypal.adaptive.class.php');

	// Create PayPal object.
	$PayPalConfig = array(
	 'Sandbox' => $sandbox,
	 'DeveloperAccountEmail' => $developer_account_email,
	 'ApplicationID' => $application_id,
	 'DeviceID' => $device_id,
	 'IPAddress' => $_SERVER['REMOTE_ADDR'],
	 'APIUsername' => $api_username,
	 'APIPassword' => $api_password,
	 'APISignature' => $api_signature,
	 'APISubject' => $api_subject
	);

	$PayPal = new PayPal_Adaptive($PayPalConfig);

// Prepare request arrays
	$PayRequestFields = array(
	 // Required.  Whether the request pays the receiver or whether the request 
	 // is set up to create a payment request, but not fulfill the payment until 
	 // the ExecutePayment is called.  Values are:  PAY, CREATE, PAY_PRIMARY
	 'ActionType' => 'PAY',
	 // Required.  The URL to which the sender's browser is redirected if the 
	 // sender cancels the approval for the payment after logging in to paypal.com.
	 // 1024 char max.
	 'CancelURL' => $domain . '?page=cart&title=store&name=Warenkorb&cart=store',
	 // Required.  3 character currency code.
	 'CurrencyCode' => CURRENCY_CODE,
	 // The payer of the fees.  Values are:  SENDER, PRIMARYRECEIVER, EACHRECEIVER,
	 // SECONDARYONLY
	 'FeesPayer' => 'EACHRECEIVER',
	 // The URL to which you want all IPN messages for this payment to be sent.
	 // 1024 char max.
	 'IPNNotificationURL' => '',
	 // A note associated with the payment (text, not HTML).  1000 char max
	 'Memo' => _('Thank you for shopping with us.'),
	 // The sender's personal id number, which was specified when the sender signed up 
	 // for the preapproval
	 'Pin' => '',
	 // The key associated with a preapproval for this payment.  
	 // The preapproval is required if this is a preapproved payment.  
	 'PreapprovalKey' => '',
	 // Required.  The URL to which the sener's browser is redirected after approvaing 
	 // a payment on paypal.com.  1024 char max.
	 'ReturnURL' => $domain . '?page=cart&title=save&name=Warenkorb&cart=save',
	 // Whether to reverse paralel payments if an error occurs with a payment.  
	 // Values are:  TRUE, FALSE
	 'ReverseAllParallelPaymentsOnError' => 'FALSE',
	 // Sender's email address.  127 char max.
	 // ?
	 'SenderEmail' => '',
	 // Unique ID that you specify to track the payment.  127 char max.
	 'TrackingID' => $_SESSION['trackingnumberx']
	);

	$ClientDetailsFields = array(
	 // Your ID for the sender  127 char max.
	 'CustomerID' => $customer['orderer_id'],
	 // Your ID of the type of customer.  127 char max.
	 'CustomerType' => 'Customer',
	 // Sender's geographic location
	 'GeoLocation' => '',
	 // A sub-identification of the application.  127 char max.
	 'Model' => '',
	 // Your organization's name or ID
	 'PartnerName' => COMPANY_NAME
	);

	$FundingTypes = array('ECHECK', 'BALANCE', 'CREDITCARD');

	$Receivers = array();
	$Receiver = array(
	 // Required.  Amount to be paid to the receiver.
	 'Amount' => $_SESSION['orderpricex'],
	 // Receiver's email address. 127 char max.
	 'Email' => $developer_account_email, //COMPANY_EMAIL,
	 // The invoice number for the payment.  127 char max.
	 'InvoiceID' => $_SESSION['ordernumberx'],
	 // Transaction type.  Values are:  GOODS, SERVICE, PERSONAL, CASHADVANCE, DIGITALGOODS
	 'PaymentType' => 'GOODS',
	 // The transaction subtype for the payment.
	 'PaymentSubType' => '',
	 // Receiver's phone number.   Numbers only.
	 'Phone' => array('CountryCode' => '', 'PhoneNumber' => '', 'Extension' => ''),
	 // Whether this receiver is the primary receiver.  Values are boolean:  TRUE, FALSE
	 'Primary' => 'false'
	);
	array_push($Receivers, $Receiver);

	// If TRUE, use credentials to identify the sender.  Default is false.
	$SenderIdentifierFields = array(
	 'UseCredentials' => 'TRUE'
	);

	$AccountIdentifierFields = array(
	 // Sender's email address.  127 char max.
	 'Email' => $customer['orderer_email'],
	 // Sender's phone number.  Numbers only.
	 'Phone' => array('CountryCode' => '', 'PhoneNumber' => '', 'Extension' => '')
	);

	$InvoiceItem = array(
	 'Name' => '', // Name of item.
	 'Identifier' => '', // External reference to item or item ID.
	 'Price' => '', // Total of line item.
	 'ItemPrice' => '', // Price of an individual item.
	 'ItemCount' => '' // Item QTY
	);


	$PayPalRequestData = array(
	 'PayRequestFields' => $PayRequestFields,
	 'ClientDetailsFields' => $ClientDetailsFields,
	 //'FundingTypes' => $FundingTypes, 
	 'Receivers' => $Receivers,
	 'SenderIdentifierFields' => $SenderIdentifierFields,
	 'AccountIdentifierFields' => $AccountIdentifierFields,
	 'InvoiceItem' => $InvoiceItem
	);

	// Pass data into class for processing with PayPal and load the response 
	// array into $PayPalResult
	$PayPalResult = $PayPal->Pay($PayPalRequestData);

	// Write the contents of the response array to the screen for demo purposes.
	echo '<pre />';
	print_r($PayPalResult);

	if ($PayPalResult["Ack"] === 'Success' and
		$PayPalResult["PaymentExecStatus"] === 'CREATED' and
		!empty($PayPalResult["RedirectURL"]))
	{
		$_SESSION['payedx'] = TRUE;
		header('location: ' . $PayPalResult["RedirectURL"]);
		exit;
	}
	else
	{
		$_SESSION['payedx'] = FALSE;
		// TODO: What to do if payment failed...
	}
	language::restTextDomain();
}

/**
 * Returns comment of this payment, this comment are saved
 * in the payment-table 
 */
function paypal_comment($paymentId)
{
	db::getInstance()->where('payment_id', $paymentId);
	$comment = db::getInstance()->getOne('payment');
	
	return $comment['payment_table'];
}

?>